package com.lixm.netty.day1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

/**
 * @author dc
 * @title: TimeServerHandle
 * @projectName netty
 * @date 2021/7/817:14
 */
public class TimeServerHandle implements Runnable{


    private Socket socket;
    private BufferedReader in = null;
    private PrintWriter out = null;


    public TimeServerHandle(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            out = new PrintWriter(this.socket.getOutputStream(), true);

            String createTime = null;
            String body = null;

            while (true) {
                body = in.readLine();
                if (body == null) {
                    break;
                }
                System.out.println("The TimeServer receive order :" + body);
                createTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
                out.println(createTime);
            }
        } catch (Exception e) {
            release();
        } finally {
            release();
        }
    }

    /**
     * 释放资源
     * @throws IOException
     */
    private void release()  {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
                out = null;
            }
            if (this.socket != null) {
                this.socket.close();
                this.socket = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
